package com.net.okhttphelper.http;

import android.text.TextUtils;
import android.util.Log;

import com.net.okhttphelper.constant.ErrorEnum;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 封装一层OkHttp回调，用于处理一些通用情况
 * @author jie
 */
public class CommonCallBack implements Callback {

    private static final String TAG = "CommonCallBack";

    protected DataCallBack mDataCallBack;

    public CommonCallBack(DataCallBack dataCallBack){
        this.mDataCallBack = dataCallBack;
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        if (call.isCanceled()){
            // 网络请求被取消，不需要做处理
            Log.w(TAG, "onFailure: 取消网络请求：" + call.request().tag().toString());
        }else{
            Throwable throwable = e.getCause();
            Log.e(TAG, "onFailure: ", e);
            if (mDataCallBack != null){
                ExceptionHandle.handleException(throwable, mDataCallBack);
            }
        }
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) {
        if (mDataCallBack != null){
            try{
                String responseStr = response.body().string().trim();
                if (!TextUtils.isEmpty(responseStr)){
                    mDataCallBack.success(responseStr);
                }else{
                    mDataCallBack.fail(ErrorEnum.ERROR_EMPTY_DATA.getCode(), ErrorEnum.ERROR_EMPTY_DATA.getMessage());
                }
            }catch (Exception e){
                e.printStackTrace();
                ExceptionHandle.handleException(e.getCause(), mDataCallBack);
            }
        }
    }
}
